package com.jsgt.greekfire.ui.home.transfer

import android.app.Dialog
import android.text.TextUtils
import android.widget.EditText
import android.widget.ImageView
import android.widget.TextView
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModelProvider
import com.fhx.core.base.BaseActivity
import com.fhx.core.utils.DialogUtil
import com.fhx.core.utils.PriceFormatUtil
import com.fhx.core.utils.ToastUtils
import com.jsgt.greekfire.BuildConfig
import com.jsgt.greekfire.R
import com.jsgt.greekfire.WALLET_ADDRESS
import com.jsgt.greekfire.dialog.SecurityPwdDialog
import com.jsgt.greekfire.event.AssetsEvent
import com.jsgt.greekfire.factory.CoinViewModelFactory
import com.jsgt.greekfire.factory.UserViewModelFactory
import com.jsgt.greekfire.common.util.NetDataManager
import com.jsgt.greekfire.viewmodel.CoinViewModel
import com.jsgt.greekfire.viewmodel.UserViewModel
import kotlinx.android.synthetic.main.activity_transfer_activation.*
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode

/**
 * 转账激活
 */
class TransferActivationActivity : BaseActivity() {
    private val userViewModel: UserViewModel by lazy {
        ViewModelProvider(
            this,
            UserViewModelFactory()
        ).get(UserViewModel::class.java)
    }
    private val coinViewModel: CoinViewModel by lazy {
        ViewModelProvider(
            this,
            CoinViewModelFactory()
        ).get(CoinViewModel::class.java)
    }
    private var pwdDialog: SecurityPwdDialog? = null

    private var pwdDialog1: Dialog? = null
    private var LOW_SUM = 0.1f//最低可输入金额
    var glb_balance = 0.0
    override fun getLayoutId(): Int = R.layout.activity_transfer_activation

    override fun main() {

//        pop()
        title = getString(R.string.activates_transfer)
        sum_et.numberDot = 1
        sum_et.requestFocus()
        confirm_tv.setOnClickListener {
            submit()
        }
        userViewModel.activityTransferLiveData.observe(this, Observer {
            showProgress(false)
            ToastUtils.show(this, "转账成功")
            pwdDialog?.dismiss()
            finish()
        })
        userViewModel.errorLiveData.observe(this, Observer {
            showProgress(false)
        })
        coinViewModel.getManagerCharge("1,2")
        coinViewModel.managerChargeLiveData.observe(this, Observer {
            for (i in it) {
                if (TextUtils.equals(i.assetName, "管理币")) {
                    LOW_SUM = i.price?.toFloat()!!
                    break
                }
            }
        })
        NetDataManager.getUserAssets()
    }

    private fun transfer(pwd: String) {
        val address = to_user_id_et.text.toString().trim()
        val sum = sum_et.text.toString().trim()
        showProgress(true)
        userViewModel.activityTransfer(address, sum, pwd)
        finish()
    }

    private fun initDialog() {
        pwdDialog = SecurityPwdDialog(this, R.style.dialog)
        pwdDialog?.inputCallback = object : SecurityPwdDialog.InputCallback {
            override fun callBack(result: String) {
                transfer(result)
            }
        }
    }

    private fun submit() {
        val sum = sum_et.text.toString()
        val address = to_user_id_et.text.toString().trim()
        if (TextUtils.isEmpty(sum)) {
            ToastUtils.show(this, "请输入转账金额")
            return
        }
        if (!TextUtils.isEmpty(sum) && sum.toFloat() <= 0) {
            ToastUtils.show(this, "金额必须大于0")
            return
        }
        if (LOW_SUM > sum.toFloat()) {
            ToastUtils.show(this, "金额不能小于${LOW_SUM}")
            return
        }
        if (glb_balance < sum.toDouble()) {
            ToastUtils.show(this, "余额不足")
            return
        }
        if (TextUtils.isEmpty(address)) {
            ToastUtils.show(this, "请输入接收地址")
            return
        }
        if (!address.startsWith(BuildConfig.WALLET_PRIVATE_KEY_START) || address.length != 36) {
            ToastUtils.show(this, "转账地址有误")
            return
        }
        if (TextUtils.equals(address, WALLET_ADDRESS)) {
            ToastUtils.show(this, "不能给自己转账")
            return
        }
        initDialog()
        pwdDialog?.numberTv?.text = sum
        pwdDialog?.nameTv?.text = "GLB"
        pwdDialog?.show()
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    fun onAssetsEvent(e: AssetsEvent) {
        for (bean in NetDataManager.assetsList) {
            if (TextUtils.equals("1", bean.assetGuid)) {
                glb_balance = bean.assetBalance!!
                sum_et.hint = "余额：${PriceFormatUtil.format(glb_balance, 2)}"
                break
            }
        }
    }

    fun pop() {
        val contentView = layoutInflater.inflate(R.layout.dialog_transfer_pop, null, false)
        pwdDialog1 = DialogUtil.show(this, contentView)
        pwdDialog1?.setOnDismissListener {
            pwdDialog1 = null
        }
        pwdDialog1?.setCancelable(true)
        pwdDialog1?.show()
        contentView.findViewById<ImageView>(R.id.close_iv).setOnClickListener {
            pwdDialog1?.dismiss()
        }

        contentView.findViewById<TextView>(R.id.check_pwd_tv).setOnClickListener {
            val pwd = contentView.findViewById<EditText>(R.id.pwd_et).text.toString().trim()
            if (TextUtils.isEmpty(pwd)) {
                showToast("密码不能为空")
            } else {
//                //服务端验证
//                walletViewModel.checkWalletSecurityPwd(pwd)
                pwdDialog1?.dismiss()
                showProgress(true)
            }
        }

    }
}